﻿namespace LeadMaster.Controllers
{
    using System;
    using System.Linq;
    using System.Web.Mvc;
    using LeadMaster.DAL;
    using LeadMaster.ViewModels;
    using System.Web.Security;
    using LeadMaster.Helpers;
    using System.Collections.Generic;
    using LeadMaster.Models;
    using System.Data;
    using LeadMaster.Properties;
    using System.Configuration;
    using System.Data.Entity;
    using System.Data.Entity.Core.Objects;
    using PagedList;

  public class ClientController : Controller
    {

      private DunsmoreContext db = new DunsmoreContext();

      private int GetID()
      {
        // returns the company id user is responsible for
        Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
        int clientID = db.ClientUsers.Where(m => m.UserID == currentUser).Select(m => m.CompanyID).FirstOrDefault();
        return clientID;
      }

      public ActionResult ViewLeads()
      {
        Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
        string userName = db.Users.Where(m => m.UserID == currentUser).FirstOrDefault().UserName;
        CallCentres cc = db.CallCentres
                          .Where(m => m.UserName == userName)
                          .FirstOrDefault();
        if (cc.Category=="N")
        {
          ViewBag.SectorID = new SelectList(db.Sectors
                                          .Join(db.Leads, a => a.SectorID, b => b.SectorID, (a, b) => new { a, b })
                                          .Join(db.LeadStatus, c => c.b.LeadID, d => d.LeadID, (c, d) => new { c, d })
                                          .Where(w => w.d.LeadFlagsID > 1)
                                          .Where(w => w.d.ResponsibleID==cc.CallCentreID)
                                          .Select(m => m.c.a)
                                          .Distinct()
                                          , "SectorID", "Sector");
        }
        else if (cc.Category=="C" && cc.ApplicableSectors!=null)
        {
          List<int> sectorFlags = new List<int>();
          foreach (var item in cc.ApplicableSectors.Split(','))
          {
            sectorFlags.Add(Convert.ToInt16(item));
          } 
          ViewBag.SectorID = new SelectList(db.Sectors
                                          .Join(db.Leads, a => a.SectorID, b => b.SectorID, (a, b) => new { a, b })
                                          .Join(db.LeadStatus, c => c.b.LeadID, d => d.LeadID, (c, d) => new { c, d })
                                          .Where(w => w.d.LeadFlagsID > 1 && sectorFlags.Contains(w.c.b.SectorID))
                                          .Select(m => m.c.a)
                                          .Distinct()
                                          , "SectorID", "Sector");
        }
        else
        {
          ViewBag.SectorID = new SelectList(db.Sectors
                                          .Join(db.Leads, a => a.SectorID, b => b.SectorID, (a, b) => new { a, b })
                                          .Join(db.LeadStatus, c => c.b.LeadID, d => d.LeadID, (c, d) => new { c, d })
                                          .Where(w => w.d.LeadFlagsID > 1)
                                          .Select(m => m.c.a)
                                          .Distinct()
                                          , "SectorID", "Sector");
        }
        ViewBag.Logon = cc.LogOn;

        return View();
      }

      [HttpPost]
      public ActionResult ViewLeads(int SectorID, Guid Logon)
      {
        int LeadId = db.Leads.Where(m => m.SectorID == SectorID).FirstOrDefault().LeadID;
        CallCentres cc = db.CallCentres.Where(m => m.LogOn == Logon).FirstOrDefault();
        int RegionID = 0;
        RegionID = cc.RegionsID ?? 0;
        return RedirectToAction("FetchLeadBlock", new { leadID = LeadId, surname = "", telephone = "", postcode = "", dayfilter = "", regionid=RegionID });
      }

      public ActionResult FetchLeadBlock(int leadID = 0, string surname = "", string telephone = "", string postcode = "", string dayfilter = "", string leadref = "", string leadFilter = "", int? page = 1,int agent=0,int regionid=0,string classification="")
      {
        Maintenance.inMaintenance = false;
        try
        {
          Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
          string userName = db.Users.Where(m => m.UserID == currentUser).FirstOrDefault().UserName;
          ViewBag.personcat = db.CallCentres
                            .Where(m => m.UserName == userName)
                            .FirstOrDefault()
                            .Category;
          ViewModelClient viewModel = new ViewModelClient();
          viewModel.Leads = db.Leads.Find(leadID);
          ViewBag.LeadID = leadID;
          ViewBag.CallCentreID = viewModel.CallCentreID;
          ViewBag.surname = surname;
          ViewBag.telephone = telephone;
          ViewBag.postcode = postcode;
          ViewBag.dayFilter = dayfilter;
          ViewBag.leadref = leadref;
          ViewBag.leadfilter = leadFilter;
          ViewBag.page = page;
          ViewBag.selectedagent = agent;
          ViewBag.selectedregion = regionid;
          ViewBag.classification = classification;
          ViewBag.Agent = new SelectList(db.CallCentres.Where(m => m.Category.Equals("I")).Select(m => new { m.CallCentreID }), "CallCentreID", "CallCentreID",agent);
          ViewBag.RegionLockDown = false;
          if (regionid!=0)
          {
            ViewBag.regionid = regionid;
            ViewBag.RegionLockDown = true;
          }
          else
          {
            ViewBag.regionid = new SelectList(db.Regions, "RegionsID", "Description", regionid);
          }
          
          ViewBag.FiltersSelected = !(string.IsNullOrEmpty(surname) && string.IsNullOrEmpty(telephone) && string.IsNullOrEmpty(postcode) && dayfilter == "" && string.IsNullOrEmpty(leadref));

          return View();
        }
        catch (Exception e)
        {
          ViewBag.ErrorMessage = "Showing Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
          return View("Errormessages");
        }

      }

      [HttpPost]
      public ActionResult RefreshFetchLeadBlock(ViewModelOutsourcer viewModel, string surname = "", string telephone = "", string postcode = "", string dayfilter = "", string leadref = "", string leadFilter = "", int agent = 0, int regionid = 0, string classification = "")
      {
        return RedirectToAction("FetchLeadBlock", new { leadID = viewModel.LeadClient, surname = surname, telephone = telephone, postcode = postcode, dayfilter = dayfilter, leadref = leadref, leadFilter = leadFilter, agent=agent,regionid=regionid,classification=classification });
      }

      public ActionResult ShowLeadsByDate(int id, string surname = "", string telephone = "", string postcode = "", string dayfilter = "", string leadref = "", string leadFilter = "", int? page = 1, int agent = 0, int regionid = 0, string classification = "")
      {
        int introducerID = GetID();
        ViewBag.id = id;
        ViewBag.surname = surname;
        ViewBag.telephone = telephone;
        ViewBag.postcode = postcode;
        ViewBag.dayfilter = dayfilter;
        ViewBag.leadref = leadref;
        ViewBag.leadFilter = leadFilter;
        ViewBag.selectedagent = agent;

        Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
        string userName = db.Users.Where(m => m.UserID == currentUser).FirstOrDefault().UserName;
        CallCentres cc = db.CallCentres
                          .Where(m => m.UserName == userName)
                          .FirstOrDefault();
        ViewBag.selectedregion = cc.Category=="N" ? cc.RegionsID : regionid;
        try
        {
          ViewModelClient viewModel = new ViewModelClient();
          ViewBag.FiltersSelected = !(string.IsNullOrEmpty(surname) && string.IsNullOrEmpty(telephone) && string.IsNullOrEmpty(postcode) && dayfilter == "" && string.IsNullOrEmpty(leadref));
          int blockID = 0;
          if (string.IsNullOrEmpty(surname) && string.IsNullOrEmpty(telephone) && string.IsNullOrEmpty(postcode) && dayfilter == "" && string.IsNullOrEmpty(leadref))
          {
            return PartialView("PartialShowLeads", viewModel);
          }
          ViewBag.FiltersSelected = true;
          viewModel.Leads = db.Leads.Find(id);
          List<LeadResults> leadResults;
          switch (cc.Category)
          {
            case "C":
              leadResults = db.LeadResults
              .Join(db.LeadStatus, a => a.BlockId, b => b.BlockID, (a, b) => new { a, b })
              .Where(m => m.b.LeadFlagsID > 1)
              .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
              .Select(m => m.a)
              .OfType<LeadResults>()
              .ToList();
              break;
            case "N":
              List<string> postcodes = db.Regions.Find(cc.RegionsID).Postcodes.Split(',').ToList();
              leadResults = db.LeadResults
              .Join(db.LeadStatus, a => a.BlockId, b => b.BlockID, (a, b) => new { a, b })
              .Where(m => m.b.LeadFlagsID > 1)
              .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
              .Where(m => m.b.ResponsibleID == cc.CallCentreID || m.b.ResponsibleID == cc.OwnedBy)
              .Select(m => m.a)
              .OfType<LeadResults>()
              .ToList();
              break;
            case "D":
              leadResults = db.LeadResults
              .Join(db.LeadStatus, a => a.BlockId, b => b.BlockID, (a, b) => new { a, b })
              .Where(m => m.b.LeadFlagsID > 1 && m.b.Handover == "In Progress" && m.b.LeadFlag.WithDeaGda == true)
              .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
              .Where(m => m.b.DeaGdaID == cc.CallCentreID)
              .Select(m => m.a)
              .OfType<LeadResults>()
              .ToList();
              break;
            case "E":
              leadResults = db.LeadResults
              .Join(db.LeadStatus, a => a.BlockId, b => b.BlockID, (a, b) => new { a, b })
              .Where(m => m.b.LeadFlagsID > 1 && m.b.Handover=="In Progress" && m.b.LeadFlag.WithInstaller==true)
              .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
              .Where(m => m.b.ResponsibleID == cc.CallCentreID || m.b.ResponsibleID == cc.OwnedBy)
              .Where(m => m.b.ResponsibleID != null)
              .Select(m => m.a)
              .OfType<LeadResults>()
              .ToList();
              break;
            case "O":
              leadResults = db.LeadResults
              .Join(db.LeadStatus, a => a.BlockId, b => b.BlockID, (a, b) => new { a, b })
              .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
              .Where(m => m.b.LeadFlagsID > 1)
              .Select(m => m.a)
              .OfType<LeadResults>()
              .ToList();
              break;
            default:
              leadResults = db.LeadResults
              .Join(db.LeadStatus, a => a.BlockId, b => b.BlockID, (a, b) => new { a, b })
              .Where(m => m.b.LeadFlagsID>1)
              .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
              .Select(m => m.a)
              .OfType<LeadResults>()
              .ToList();
              break;
          }

          // is this User a Partial Postcode User ?
          if (db.BindPartialPostcodes.Any(m => m.CallCentreid==cc.CallCentreID))
          {
            leadResults = (from lr in leadResults
                           join p in db.BindPartialPostcodes on lr.BlockId equals p.BlockID
                           where p.CallCentreid == cc.CallCentreID
                           select lr)
                           .ToList();
            regionid = 0;
          }
          
          
          if (leadResults.Count() == 0)
          {
            return PartialView("PartialShowLeads", viewModel);
          }
          if (dayfilter == "7")
          {
            leadResults = (from lr in leadResults
                           join lr2 in leadResults on lr.BlockId equals lr2.BlockId
                           where lr.LeadDate >= DateTime.Now.AddDays(-7)
                           select lr2)
                          .ToList();
          }
          if (dayfilter == "1")
          {
            leadResults = (from lr in leadResults
                           join lr2 in leadResults on lr.BlockId equals lr2.BlockId
                           where lr.LeadDate >= DateTime.Now.AddDays(-1)
                           select lr2)
                          .ToList();
          }
          if (leadref != "")
          {
            blockID = Convert.ToInt16(leadref);
            leadResults = (from lr in leadResults
                           join lr2 in leadResults on lr.BlockId equals lr2.BlockId
                           where lr.BlockId == blockID
                           select lr2)
                          .ToList();
          }
          if (surname != "")
          {
            leadResults = (from lr in leadResults
                           join lr2 in leadResults on lr.BlockId equals lr2.BlockId
                           where lr.Question == "Surname" && lr.Answer.ToLower().Contains(surname.ToLower())
                           select lr2)
                          .ToList();
          }
          if (telephone != "")
          {
            leadResults = (from lr in leadResults
                           join lr2 in leadResults on lr.BlockId equals lr2.BlockId
                           where (lr.Question == "Primary Telephone Number" && lr.Answer.Replace(" ", "").Contains(telephone.Replace(" ", ""))) ||
                            (lr.Question == "Mobile or Alternate Number" && lr.Answer.Replace(" ", "").Contains(telephone.Replace(" ", "")))
                           select lr2)
                          .ToList();
          }
          if (postcode != "")
          {
            leadResults = (from lr in leadResults
                           join lr2 in leadResults on lr.BlockId equals lr2.BlockId
                           where lr.Question == "Postcode" && lr.Answer.ToLower().Contains(postcode.ToLower())
                           select lr2)
                          .ToList();
          }
          if (leadFilter == "Active")
          {
            leadResults = (from lr in leadResults
                           join ls in db.LeadStatus on lr.BlockId equals ls.BlockID
                           where ls.LeadFlag.Description != "Dead"
                           select lr)
                          .ToList();
          }
          if (leadFilter == "Dead")
          {
            leadResults = (from lr in leadResults
                           join ls in db.LeadStatus on lr.BlockId equals ls.BlockID
                           where ls.LeadFlag.Description == "Dead"
                           select lr)
                           .ToList();
          }
          if (agent != 0)
          {
            leadResults = (from lr in leadResults
                           where lr.CallCentreID==agent
                           select lr)
                           .ToList();
          }
          if (cc.Category!="N" && regionid>0)
          {
            List<string> postcodes = db.Regions.Find(regionid).Postcodes.Split(',').ToList();
            leadResults = (from lr in leadResults
                           join ls in db.LeadStatus on lr.BlockId equals ls.BlockID
                           where postcodes.Contains(ls.RegionPostcode)
                           select lr)
                           .ToList();
          }
          if (classification!="")
          {
            leadResults = (from lr in leadResults
                           join ls in db.LeadStatus on lr.BlockId equals ls.BlockID
                           where ls.SelectedClassification==classification
                           select lr)
                           .ToList();
          }

          leadResults = leadResults.Distinct().ToList();
          blockID = 0;
          LeadStatus statusBlock = db.LeadStatus.FirstOrDefault();
          LeadFlags leadFlag = db.LeadFlags.FirstOrDefault();
          LeadReasons leadReason = db.LeadReasons.FirstOrDefault();
          viewModel.FullListLeadResults = new List<ListLeadResults>();
          int totalLeads = 0;
          LeadReasons leadreason = db.LeadReasons.FirstOrDefault();
          LeadStatus leadstatus = db.LeadStatus.FirstOrDefault();
          if (leadResults.Count() > 0)
          {
            viewModel.LeadDate = leadResults.LastOrDefault().LeadDate;
            foreach (LeadResults item in leadResults.OrderBy(m => m.BlockId).ThenBy(m => m.DisplayOrder))
            {
              if (blockID!=item.BlockId)
              {
                leadstatus = db.LeadStatus.Where(m => m.BlockID == item.BlockId).FirstOrDefault();
              }
              ListLeadResults listLeadResults = new ListLeadResults();
              listLeadResults.LeadResult = item;
              listLeadResults.LeadReason = leadreason;
              listLeadResults.LeadStatus = leadstatus;
              listLeadResults.LeadFlag = leadstatus.LeadFlag;

              viewModel.FullListLeadResults.Add(listLeadResults);
            }
          }
          viewModel.GridTitlesList = new List<GridTitles>();
          
          if (viewModel.FullListLeadResults.Count() > 0)
          {
            foreach (var item in leadResults.Where(m => m.BlockId==leadResults.FirstOrDefault().BlockId))
            {
              GridTitles gridTitle=new GridTitles();
              gridTitle.Title=item.Question;
              if (item.LeadStatQuestion != null)
              {
                gridTitle.Backcolour = item.LeadStatQuestion.LeadStat.BackgroundColour;
              }
              else if (item.LeadGroupQuestion != null)
              {
                gridTitle.Backcolour = item.LeadGroupQuestion.LeadGroups.BackgroundColour;
              }
              viewModel.GridTitlesList.Add(gridTitle);
            }
          }

          ViewBag.TotalLeads = totalLeads;
          if (Session["PersonType"].ToString()=="C")
          {
            viewModel.ListLeadFlags = db.LeadFlags.Where(m => m.WithClient == true).OrderBy(m => m.DisplayOrder).ToList();
            viewModel.ListInstallers = db.CallCentres.Where(m => m.Category == "N").ToList();
            viewModel.ListDeaGda = db.CallCentres.Where(m => m.Category == "D").ToList();  
          }
          else
	        {
            string personType = Session["PersonType"].ToString();
            switch (personType)
            {
              case "N":
                viewModel.ListLeadFlags = db.LeadFlags.Where(m => m.WithInstaller==true).OrderBy(m => m.DisplayOrder).ToList();
                break;
              case "D":
                viewModel.ListLeadFlags = db.LeadFlags.Where(m => m.WithDeaGda == true).OrderBy(m => m.DisplayOrder).ToList();
                break;
              case "O":
                viewModel.ListLeadFlags = db.LeadFlags.OrderBy(m => m.DisplayOrder).ToList();
                break;
              default:
                break;
            }
	        }

          viewModel.ListEngineers = db.CallCentres.Where(m => m.Category == "E").ToList();
          ViewBag.PersonType = Session["PersonType"];
          if (Request.HttpMethod != "GET")
          {
            page = 1;
          }
          int pageNumber = (page ?? 1);
          if (viewModel.FullListLeadResults == null || viewModel.FullListLeadResults.Count() == 0)
          {
            return PartialView("NoLeads");
          }
          
          var onePageOfLeads = viewModel.FullListLeadResults.ToPagedList(pageNumber, viewModel.FullListLeadResults.FirstOrDefault().LeadResult.QuestionBlock * 10);
          
          ViewBag.LeadsPage = onePageOfLeads;

          return PartialView("PartialShowLeads", viewModel);
          }
          catch (Exception e)
          {
            ViewBag.ErrorMessage = "Showing Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
              return View("Errormessages");
          }
      }

	  public ActionResult PlayVoxFile(string voxFile)
	  {
		  var file = Server.MapPath("~/Vox/" + voxFile);
          if (voxFile.Substring(voxFile.Length-3,3).Equals("mp3"))
          {
              return File(file, "audio/mp3");    
          }
          else
          {
              return File(file, "audio/wav");    
          }
		  
	  }

      public ActionResult Tracker()
      {
        int companyID = GetID();
        int leadID = db.Leads.Where(m => m.CompanyID == companyID).FirstOrDefault().LeadID;
        return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fClientTracker&rs:Command=Render&l=" + leadID.ToString());
      }


      public void UpdateClientNote(int id,string notetext)
      {
          LeadStatus ls = db.LeadStatus.Find(id);
          ls.ClientNotes=notetext;
          db.Entry(ls).State=EntityState.Modified;
          db.SaveChanges();
      }

      [HttpGet]
      public void ChangeFunding(int leadstatusid, string fundingvalue)
      {
        LeadStatus ls = db.LeadStatus.Find(leadstatusid);
        ls.Funding = fundingvalue;
        db.Entry(ls).State = EntityState.Modified;
        db.SaveChanges();
      }

      [HttpGet]
      public void ChangeHandover(int leadstatusid, string handovervalue)
      {
        LeadStatus ls = db.LeadStatus.Find(leadstatusid);
        ls.Handover = handovervalue;
        db.Entry(ls).State = EntityState.Modified;
        db.SaveChanges();
      }

      [HttpGet]
      public void Dead(int leadstatusid, bool deadvalue)
      {
        LeadStatus ls = db.LeadStatus.Find(leadstatusid);
        ls.Dead = deadvalue;
        db.Entry(ls).State = EntityState.Modified;
        db.SaveChanges();
      }

      [HttpGet]
      public void FreePaid(int leadstatusid, string freePaid)
      {
        LeadStatus ls = db.LeadStatus.Find(leadstatusid);
        ls.FreePaid = freePaid;
        LeadResults lr = db.LeadResults.Where(m => m.BlockId == ls.BlockID && (m.Answer == "Free" || m.Answer == "Paid")).FirstOrDefault();
        lr.Answer = freePaid;
        db.Entry(lr).State = EntityState.Modified;
        db.Entry(ls).State = EntityState.Modified;
        db.SaveChanges();
      }

      public static string GetColourCode(LeadFlags leadFlag)
      {
        string colourCode;
        if (leadFlag.WithInstaller??false==true)
        {
          colourCode = "535253";
        }
        else if (leadFlag.WithDeaGda ?? false == true)
        {
          colourCode = "535253";
        }
        else
        {
          colourCode = "000000";
        }
        
        return "color: #" + colourCode + ";";
      }

      [System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
      public FileStreamResult ShowExcel(string reportname = "CallCentreStats")
      {
        int companyID = GetID();
        int leadID = db.Leads.Where(m => m.CompanyID == companyID).FirstOrDefault().LeadID;
        string excelname = db.Companies.Find(companyID).Company ;
        // Create a new proxy to the web service
        rsExecService.ReportExecutionService rsExec = new rsExecService.ReportExecutionService();
        // Authenticate to the web service using windows credentials
        rsExec.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["UserID"], ConfigurationManager.AppSettings["Pwd"]);
        // Load the selected report
        rsExec.LoadReport("/dunsmore/" + reportname, null);

        // Prepare Render arguments
        string encoding = String.Empty;
        string mimeType = String.Empty;
        string extension = String.Empty;
        rsExecService.Warning[] warnings = null;
        string[] streamIDs = null;

        // Prepare report parameters.
        rsExecService.ParameterValue[] parameters = new rsExecService.ParameterValue[1];
        parameters[0] = new rsExecService.ParameterValue();
        parameters[0].Value = leadID.ToString();
        parameters[0].Name = "leadid";

        // Set the parameters for the report needed.
        rsExec.SetExecutionParameters(parameters, "en-us");

        //Render the report to a byte[]
        Byte[] byteInfo = rsExec.Render("Excel", null, out extension, out encoding, out mimeType, out warnings, out streamIDs);

        // Return the report as a file stream
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        ms.Write(byteInfo, 0, byteInfo.Length);
        ms.Position = 0;

        HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + excelname + ".xls");

        return new FileStreamResult(ms, ConfigurationManager.AppSettings["ReportName"]);

      }

      public static string StreetviewLatLong(int leadStatusID)
      {
        DunsmoreContext db = new DunsmoreContext();
        LeadStatus leadStatus = db.LeadStatus.Find(leadStatusID);
        string postCode = db.LeadResults
            .Where(m => m.LeadID == leadStatus.LeadID && m.BlockId == leadStatus.BlockID && m.Question == "Postcode")
            .Select(m => m.Answer)
            .FirstOrDefault();
        PostCodes postCodes = db.Postcodes.Where(m => m.Postcode == postCode.Replace(" ", "")).FirstOrDefault();
        string returnString = postCodes != null ? (postCodes.lat.ToString() + "," + postCodes.longitude.ToString()) : string.Empty;
        return returnString;
      }

      public static string StreetviewPostcode(int leadStatusID)
      {
        DunsmoreContext db = new DunsmoreContext();
        LeadStatus leadStatus = db.LeadStatus.Find(leadStatusID);
        string postCode = db.LeadResults
            .Where(m => m.LeadID == leadStatus.LeadID && m.BlockId == leadStatus.BlockID && m.Question == "Postcode")
            .Select(m => m.Answer)
            .FirstOrDefault();
        string returnString = postCode;
        return returnString;
      }

      public ActionResult Escalate(int leadStatusID)
      {
          LeadStatus leadStatus = db.LeadStatus.Find(leadStatusID);
          return PartialView(leadStatus);
      }

      public ActionResult NewNote(int id)
      {
        LeadStatus leadStatus = db.LeadStatus.Find(id);
        return PartialView("AddNote",leadStatus);
      }

      [HttpPost]
      public void NewNote(LeadStatus leadStatus, string NewNote)
      {
        ViewModelOutsourcer viewModel = new ViewModelOutsourcer();

        if (ModelState.IsValid)
        {
          LeadStatus ls = db.LeadStatus.Find(leadStatus.LeadStatusID);
          Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
          string agent;
          Users user = db.Users.Where(m => m.UserID == currentUser).FirstOrDefault();
          agent = db.CallCentres.Where(m => m.UserName == user.UserName).FirstOrDefault().Contact1;
          string newNote = string.Format("{0} {1} : {2}", agent, DateTime.Today.ToShortDateString(), NewNote);
          ls.Notes += "\n" + newNote;
          db.Entry(ls).State = EntityState.Modified;
          db.SaveChanges();
        }
      }


      public JsonResult FetchClientNote(int leadStatusID)
      {
        LeadStatus ls = db.LeadStatus.Find(leadStatusID);
        return Json(ls.Notes, JsonRequestBehavior.AllowGet);
      }

      public void SaveResponsibility(int leadStatusID, int installerID)
      {
        LeadStatus ls = db.LeadStatus.Find(leadStatusID);
        ls.ResponsibleID = installerID;
        db.Entry(ls).State = EntityState.Modified;
        db.SaveChanges();
      }

      public void SaveClassification(int leadStatusID, string selectedclassification)
      {
        LeadStatus ls = db.LeadStatus.Find(leadStatusID);
        ls.SelectedClassification = selectedclassification;
        db.Entry(ls).State = EntityState.Modified;
        db.SaveChanges();
      }
    
      public void SaveDeaGda(int leadStatusID, int installerID)
      {
        LeadStatus ls = db.LeadStatus.Find(leadStatusID);
        ls.DeaGdaID = installerID;
        db.Entry(ls).State = EntityState.Modified;
        db.SaveChanges();
      }

      [HttpGet]
      public JsonResult ChangeLeadStatus(int leadstatusid, int statusvalue)
      {
        LeadStatus ls = db.LeadStatus.Find(leadstatusid);
        ls.LeadFlagsID = statusvalue;
        ls.LeadFlag = db.LeadFlags.Find(statusvalue);
        ls.Handover = ls.LeadFlag.WithInstaller==true || ls.LeadFlag.WithDeaGda==true ? "In Progress" : "";
        ls.UserID = (Guid)Membership.GetUser().ProviderUserKey;
        db.Entry(ls).State = EntityState.Modified;
        db.SaveChanges();
        string retValue;
        if (ls.LeadFlag.WithInstaller==true)
        {
          retValue = "installer";
        }
        else if (ls.LeadFlag.WithDeaGda == true)
        {
          retValue = "deagda";
        }
        else
        {
          retValue = "lye";
        }
        return Json(retValue, JsonRequestBehavior.AllowGet);
      }

    }
}
